package com.yunc.base;

import cn.hutool.core.collection.CollectionUtil;
import com.yunc.base.utils.AuthConstants;
import com.yunc.modules.sys.entity.dto.SysRoleMenuDTO;
import com.yunc.modules.sys.service.ISysRoleMenuService;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.ApplicationArguments;
import org.springframework.boot.ApplicationRunner;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

@Slf4j
@Component
@RequiredArgsConstructor(onConstructor = @__(@Autowired))
public class InitResourceRolesRunner implements ApplicationRunner {

    private final RedisTemplate<String, Object> redisTemplate;
    private final ISysRoleMenuService sysRoleMenuService;

    @Override
    public void run(ApplicationArguments args) {
        log.info("init resource roles");
        // 先删除权限
        redisTemplate.delete(AuthConstants.RESOURCE_ROLES_KEY);
        // 加载权限进入
        Map<String, List<String>> resourceRolesMap = new TreeMap<>();
        // 查询所有
        List<SysRoleMenuDTO> list = sysRoleMenuService.queryRoleMenuPerms();

        if (CollectionUtil.isNotEmpty(list)) {
            for (SysRoleMenuDTO roleMenu : list) {
                String[] arr = roleMenu.getRoleIds().split(",");
                if (arr.length == 0) {
                    continue;
                }
                List<String> roles = new ArrayList<>();
                for (String roleId : arr) {
                    roles.add(AuthConstants.AUTHORITY_PREFIX + roleId);
                }
                resourceRolesMap.put(roleMenu.getMenuPerms(), roles);
                redisTemplate.opsForHash().putAll(AuthConstants.RESOURCE_ROLES_KEY, resourceRolesMap);
            }
        }

    }
}
